from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import requests
import time
import cv2

#
driver=webdriver.Chrome()
driver.implicitly_wait(10)
#模拟人的滑动行为
def track(distance):
    #动作轨迹，先匀加速后匀减速。
    #基本计算公式:v=v0+at,s=v0t+1/2 at的平方，v的平方-v0的平方=2as
    v=0
    t=0.3
    tracks=[]
    current=0
    #到达mid点开始减速
    mid=distance*4/5
    while current<distance:
        if current<mid:
            a=2
        else:
            a=-3
        v0=v
        s=v0*t+0.5*a*(t**2)
        #当前位置
        current+=s
        #需要移动的距离
        tracks.append(round(s))
        v=v0+a*t
    return tracks


while True:
    driver.get('https://www.douban.com')
    #由于定位不到网页中的密码登录，需要找到登录界面
    iframe = driver.find_element(by=By.XPATH,value='//div[@class="login"]/iframe')
    # 切换到iframe
    driver.switch_to.frame(iframe)
    # 点击密码登陆
    driver.find_element(by=By.CLASS_NAME,value="account-tab-account").click()
    #传入账号和密码
    driver.find_element(by=By.ID,value='username').send_keys('13471479481')
    #密码
    driver.find_element(by=By.ID,value='password').send_keys('moqiaoli123926')

    #点击登录
    driver.find_element(by=By.XPATH,value='/html/body/div[1]/div[2]/div[1]/div[5]/a').click()
    time.sleep(2)
    #解决滑动验证码问题
    driver.switch_to.frame(driver.find_element(By.XPATH,'//*[@id="tcaptcha_iframe"]'))
    #获取图片地址
    big_img=driver.find_element(By.XPATH,'//*[@id="cdn1"]')
    big_url=big_img.get_attribute('src')
    small_img=driver.find_element(By.XPATH,'//*[@id="cdn2"]')
    small_url=small_img.get_attribute('src')

    #下载图片
    def save_img(url,name):
        with open(name+'.jpg','wb') as f:
            f.write(requests.get(url).content)
            f.close

    save_img(big_url,'big_img')
    save_img(small_url,'small_img')

    #匹配滑板和小图重叠的距离
    #读取图片
    big_gray=cv2.imread('big_img.jpg',0)
    small_gray=cv2.imread('small_img.jpg',0)

    # #模板匹配
    res=cv2.matchTemplate(big_gray,small_gray,cv2.TM_CCOEFF_NORMED)
    # #匹配原图小图和大图最左最右边的距离
    value=cv2.minMaxLoc(res)
    x=value[2][0]

    #计算偏移量和实际，原图大小为680*390，实际大小为282*162
    x=int(x * 282 /  680)#缩放比例
    py=31-int(20*282 / 680)#偏移量
    x=x-py
    print(x)
    #动作链
    hk=driver.find_element(By.XPATH,'//*[@id="tcaptcha_drag_thumb"]')
    action=ActionChains(driver)#初始化一个鼠标对象
    action.click_and_hold(hk).perform()#鼠标按住不动
    action.move_to_element_with_offset(hk,x-35,0).perform()#把滑块滑动到指定位置
    tracks=track(60)
    print(tracks)
    for i in tracks:
        ActionChains(driver).move_by_offset(i,0).perform()
        #释放
    time.sleep(2)
    ActionChains(driver).release().perform()

    try:
        driver.find_element(By.XPATH,'//*[@id="reload"]/div')
    except Exception as e:
        break




